from flask import Flask, request, jsonify
from flask import request
import database.newsdb
from test.test2 import interactive_session
from flask_cors import CORS
import webbrowser
from werkzeug.utils import secure_filename
import os
from pymongo import MongoClient
import gridfs
import database.newsdb
app = Flask(__name__)
CORS(app)

client = MongoClient('mongodb://localhost:27017/')
db = client['news_detail']  # 替换为你的数据库名称

@app.route('/')
def hello_world():
    return 'Hello, World!'


@app.route('/question', methods=['POST'])
def get_question():
    data = request.json
    data=data['data']
    print(data)
    question=data
    ans=interactive_session(question)
    return ans

@app.route('/insert_new',methods=['POST'])
def insert_new():
    data=request
    res = database.newsdb.insertnews(data)
    return res


@app.route('/news_show',methods=['POST'])
def news_show():
    req=request.get_json()
    code=req.get('code')
    newclass=req.get('class')
    data=database.newsdb.get_news(code,newclass)
    return data

@app.route('/get_newsdetail',methods=['POST'])
def news_content():
    data = request.get_json()
    title=data.get('title')
    data=database.newsdb.get_data_with_files(title)
    return data

@app.route('/news_delete',methods=['POST'])
def news_delete():
    data = request.get_json()
    title=data.get('title')
    print(title)
    return data

#上传文件接口测试
@app.route('/up_file/', methods=['POST'])
def get_file():
    if 'file' not in request.files:
        print("error")
        return jsonify({'message': 'No file part in the request'}), 400
    
    file = request.files['file']
    
    # 确保data目录存在
    if not os.path.exists('data'):
        os.makedirs('data')
    # 保存文件到data目录
    filename = secure_filename(file.filename)
    file.save(os.path.join('data', filename))
    return jsonify({"code":101})


if __name__ == '__main__':
    #app.run(debug=True)
    app.run(host='127.0.0.1', port=5000)